﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    ViewData["Title"] = "物料分类管理";
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>物料分类管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="~/scripts/layui-v2.5.6/layui/layui.js"></script>
    <link href="~/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
    <style>
        body { padding: 15px; background-color: #f2f2f2; }
        .layui-fluid { padding: 15px; }
        .layui-card { box-shadow: 0 1px 2px 0 rgba(0,0,0,.05); }
        .search-area { margin-bottom: 10px; background: #fff; padding: 15px; border-radius: 2px; }
        .tree-table-cell { display: flex; align-items: center; }
        .tree-indent { display: inline-block; width: 20px; }
        .tree-icon { display: inline-block; width: 16px; height: 16px; line-height: 16px; text-align: center; margin-right: 5px; cursor: pointer; font-size: 14px; color: #666; }
        .tree-icon.no-children { visibility: hidden; }
        .loading-text { text-align: center; padding: 50px; color: #999; }
    </style>
</head>
<body>
    <div class="layui-fluid">
        <div class="layui-card">
            <div class="layui-card-body">
                <!-- 搜索栏 -->
                <div class="search-area">
                    <form class="layui-form layui-form-pane" lay-filter="searchForm">
                        <div class="layui-form-item">
                            <div class="layui-inline">
                                <label class="layui-form-label">分类名称</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="className" placeholder="请输入分类名称" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-inline">
                                <label class="layui-form-label">是否启用</label>
                                <div class="layui-input-inline">
                                    <select name="isEnabled">
                                        <option value="">选择是或否</option>
                                        <option value="1">是</option>
                                        <option value="0">否</option>
                                    </select>
                                </div>
                            </div>
                            <div class="layui-inline">
                                <button type="button" class="layui-btn" lay-submit lay-filter="search">
                                    <i class="layui-icon layui-icon-search"></i> 搜索
                                </button>
                                <button type="reset" class="layui-btn layui-btn-primary">
                                    <i class="layui-icon layui-icon-refresh"></i> 重置
                                </button>
                            </div>
                        </div>
                    </form>
                </div>

                <!-- 工具栏 -->
                <script type="text/html" id="toolbarDemo">
                    <div class="layui-btn-container">
                        <button class="layui-btn layui-btn-sm" lay-event="toggleExpand" id="toggleExpandBtn">
                            <i class="layui-icon layui-icon-down"></i> 展开/折叠
                        </button>
                        <button class="layui-btn layui-btn-normal layui-btn-sm" lay-event="add">
                            <i class="layui-icon layui-icon-add-1"></i> 新增分类
                        </button>
                    </div>
                </script>

                <!-- 表格 -->
                <div id="loadingDiv" class="loading-text">
                    <i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i>
                    正在加载数据...
                </div>
                <table id="materialClassTable" lay-filter="materialClassTable" style="display:none;"></table>
            </div>
        </div>
    </div>

    <!-- 操作列模板 -->
    <script type="text/html" id="operationBar">
        <a class="layui-btn layui-btn-xs" lay-event="edit">修改</a>
        <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="add">+新增</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除</a>
    </script>

    <!-- 编辑表单 -->
    <script type="text/html" id="editFormTpl">
        <form class="layui-form" lay-filter="editForm" style="padding: 20px;">
            <input type="hidden" name="id">
            <input type="hidden" name="parentId">
            <div class="layui-form-item">
                <label class="layui-form-label">父级分类</label>
                <div class="layui-input-block">
                    <input type="text" name="parentName" disabled class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label required">分类名称</label>
                <div class="layui-input-block">
                    <input type="text" name="classifyName" required lay-verify="required" placeholder="请输入分类名称" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">显示排序</label>
                <div class="layui-input-block">
                    <input type="number" name="orderById" value="1" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label required">物料/产品</label>
                <div class="layui-input-block">
                    <input type="radio" name="materialName" value="物料" title="物料" checked>
                    <input type="radio" name="materialName" value="产品" title="产品">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">启用状态</label>
                <div class="layui-input-block">
                    <input type="radio" name="isEnabled" value="true" title="是" checked>
                    <input type="radio" name="isEnabled" value="false" title="否">
                </div>
            </div>
            <div class="layui-form-item" style="text-align: center;">
                <button class="layui-btn" lay-submit lay-filter="editFormSubmit">确定</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </form>
    </script>

    <script>
        layui.use(['table', 'form', 'layer'], function () {
            var table = layui.table,
                form = layui.form,
                layer = layui.layer;

            var allData = [];
            var expandedRows = new Set();
            var allExpanded = false;
            var currentExpandLevel = 0;
            var maxLevel = 0;
            var isExpandingMode = true;

            // 简化的数据处理
            function buildTree(data) {
                var map = {};
                var roots = [];
                
                // 建立映射
                data.forEach(function(item) {
                    item.children = [];
                    item._level = 0;
                    map[item.id] = item;
                });
                
                // 建立父子关系
                data.forEach(function(item) {
                    if (item.parentId && map[item.parentId]) {
                        map[item.parentId].children.push(item);
                        item._level = map[item.parentId]._level + 1;
                    } else {
                        roots.push(item);
                    }
                });
                
                return roots;
            }

            // 计算最大层级
            function calculateMaxLevel(data) {
                var max = 0;
                function traverse(nodes) {
                    nodes.forEach(function(node) {
                        if (node._level > max) max = node._level;
                        if (node.children && node.children.length > 0) {
                            traverse(node.children);
                        }
                    });
                }
                traverse(data);
                return max;
            }

            // 扁平化树数据
            function flattenData(treeData) {
                var result = [];
                function traverse(nodes, visible) {
                    nodes.forEach(function(node) {
                        if (visible) {
                            result.push(node);
                        }
                        if (node.children && node.children.length > 0) {
                            traverse(node.children, visible && (allExpanded || expandedRows.has(node.id)));
                        }
                    });
                }
                traverse(treeData, true);
                return result;
            }

            // 逐级展开到指定级别
            function expandToLevel(targetLevel) {
                expandedRows.clear();
                
                function expandLevel(nodes, level) {
                    if (level < targetLevel) {
                        nodes.forEach(function(node) {
                            if (node.children && node.children.length > 0) {
                                expandedRows.add(node.id);
                                expandLevel(node.children, level + 1);
                            }
                        });
                    }
                }
                
                if (targetLevel > 0) {
                    expandLevel(allData, 0);
                }
            }

            // 加载数据
            function loadData() {
                $('#loadingDiv').show();
                $('#materialClassTable').hide();
                
                // 重置状态
                expandedRows.clear();
                allExpanded = false;
                currentExpandLevel = 0;
                maxLevel = 0;
                isExpandingMode = true;
                
                $.ajax({
                    url: '/Material/GetMaterialClasses',
                    type: 'GET',
                    timeout: 15000,
                    success: function(res) {
                        $('#loadingDiv').hide();
                        if (res.code === 0 && res.data) {
                            allData = buildTree(res.data);
                            maxLevel = calculateMaxLevel(allData);
                            renderTable();
                            $('#materialClassTable').show();
                        } else {
                            layer.msg('获取数据失败: ' + (res.msg || '未知错误'));
                        }
                    },
                    error: function(xhr, status, error) {
                        $('#loadingDiv').hide();
                        layer.msg('请求失败: ' + error);
                    }
                });
            }

            // 渲染表格
            function renderTable() {
                var tableData = flattenData(allData);
                
                table.render({
                    elem: '#materialClassTable',
                    data: tableData,
                    toolbar: '#toolbarDemo',
                    defaultToolbar: [
                        {title: '刷新', layEvent: 'refresh', icon: 'layui-icon-refresh'},
                        'exports',
                        {title: '显示/隐藏搜索', layEvent: 'toggleSearch', icon: 'layui-icon-search'}
                    ],
                    cols: [[
                        { type: 'numbers', width: 60 },
                        { 
                            field: 'classifyName', 
                            title: '分类名称', 
                            minWidth: 200, 
                            templet: function(d) {
                                var indent = '';
                                for (var i = 0; i < d._level; i++) {
                                    indent += '<span class="tree-indent"></span>';
                                }
                                
                                var hasChildren = d.children && d.children.length > 0;
                                var iconClass = hasChildren ? 
                                    (allExpanded || expandedRows.has(d.id) ? 'layui-icon-down' : 'layui-icon-right') : 
                                    'no-children';
                                var icon = '<i class="layui-icon ' + iconClass + ' tree-icon" data-id="' + d.id + '"></i>';
                                
                                return '<div class="tree-table-cell">' + indent + icon + d.classifyName + '</div>';
                            }
                        },
                        { field: 'orderById', title: '排序', width: 100 },
                        { field: 'materialName', title: '物料/产品', width: 120 },
                        {
                            field: 'isEnabled', 
                            title: '是否启用', 
                            width: 100, 
                            templet: function (d) {
                                return d.isEnabled ? 
                                    '<span class="layui-badge layui-bg-blue">是</span>' : 
                                    '<span class="layui-badge layui-bg-gray">否</span>';
                            }
                        },
                        { 
                            field: 'createTime', 
                            title: '创建时间', 
                            width: 180,
                            templet: function(d) {
                                if (!d.createTime) return '';
                                var date = new Date(d.createTime);
                                return date.toLocaleString('zh-CN');
                            }
                        },
                        { title: '操作', toolbar: '#operationBar', width: 200, fixed: 'right' }
                    ]],
                    done: function () {
                        // 绑定展开/折叠事件
                        $('.layui-table-body').off('click', '.tree-icon').on('click', '.tree-icon:not(.no-children)', function(e) {
                            e.stopPropagation();
                            var id = parseInt($(this).data('id'));
                            if (expandedRows.has(id)) {
                                expandedRows.delete(id);
                            } else {
                                expandedRows.add(id);
                            }
                            renderTable();
                        });
                        
                        // 更新展开/折叠按钮状态
                        updateToggleButton();
                    }
                });
            }

            // 更新展开/折叠按钮状态
            function updateToggleButton() {
                var btn = $('#toggleExpandBtn');
                if (currentExpandLevel === 0) {
                    btn.html('<i class="layui-icon layui-icon-down"></i> 展开/折叠');
                } else if (currentExpandLevel >= maxLevel) {
                    btn.html('<i class="layui-icon layui-icon-up"></i> 展开/折叠 (全部展开)');
                } else {
                    var icon = isExpandingMode ? 'layui-icon-down' : 'layui-icon-up';
                    btn.html('<i class="layui-icon ' + icon + '"></i> 展开/折叠 (' + currentExpandLevel + '/' + maxLevel + '级)');
                }
            }

            // 工具栏事件
            table.on('toolbar(materialClassTable)', function (obj) {
                switch (obj.event) {
                    case 'toggleExpand':
                        // 智能逐级展开/折叠
                        if (isExpandingMode) {
                            // 展开模式：逐级展开
                            var nextLevel = currentExpandLevel + 1;
                            if (nextLevel > maxLevel) {
                                // 如果超过最大级别，切换到折叠模式
                                isExpandingMode = false;
                                currentExpandLevel = maxLevel;
                                allExpanded = false;
                            } else {
                                expandToLevel(nextLevel);
                                currentExpandLevel = nextLevel;
                                allExpanded = false;
                                if (nextLevel >= maxLevel) {
                                    isExpandingMode = false;
                                }
                            }
                        } else {
                            // 折叠模式：逐级折叠
                            var nextLevel = currentExpandLevel - 1;
                            if (nextLevel < 0) {
                                // 如果小于0，切换到展开模式
                                expandedRows.clear();
                                isExpandingMode = true;
                                currentExpandLevel = 0;
                                allExpanded = false;
                            } else {
                                expandToLevel(nextLevel);
                                currentExpandLevel = nextLevel;
                                allExpanded = false;
                                if (nextLevel <= 0) {
                                    isExpandingMode = true;
                                }
                            }
                        }
                        renderTable();
                        break;
                    case 'add':
                        openEditForm();
                        break;
                    case 'refresh':
                        loadData();
                        break;
                    case 'toggleSearch':
                        // 切换搜索区域显示/隐藏
                        var searchArea = $('.search-area');
                        if (searchArea.is(':visible')) {
                            searchArea.hide();
                        } else {
                            searchArea.show();
                        }
                        break;
                }
            });

            // 行工具事件
            table.on('tool(materialClassTable)', function (obj) {
                var data = obj.data;
                if (obj.event === 'edit') {
                    openEditForm(data);
                } else if (obj.event === 'add') {
                    openEditForm(null, data);
                } else if (obj.event === 'delete') {
                    layer.confirm('确定删除该分类吗？', function (index) {
                        layer.close(index);
                        deleteItem(data.id);
                    });
                }
            });

            // 删除项目
            function deleteItem(id) {
                var loadIndex = layer.load();
                $.ajax({
                    url: '/Material/DeleteMaterialClass',
                    type: 'POST',
                    data: { id: id },
                    success: function (res) {
                        layer.close(loadIndex);
                        if (res.success) {
                            layer.msg('删除成功');
                            loadData();
                        } else {
                            layer.msg(res.message || '删除失败');
                        }
                    },
                    error: function () {
                        layer.close(loadIndex);
                        layer.msg('删除失败');
                    }
                });
            }

            // 查找父节点
            function findParentNode(nodeId) {
                function searchInTree(nodes) {
                    for (var i = 0; i < nodes.length; i++) {
                        var node = nodes[i];
                        if (node.children && node.children.length > 0) {
                            for (var j = 0; j < node.children.length; j++) {
                                if (node.children[j].id === nodeId) {
                                    return node;
                                }
                            }
                            // 递归搜索子节点
                            var parent = searchInTree(node.children);
                            if (parent) return parent;
                        }
                    }
                    return null;
                }
                return searchInTree(allData);
            }

            // 打开编辑表单
            function openEditForm(data, parentData) {
                var title = data ? '修改分类' : (parentData ? '添加子分类' : '添加根分类');
                layer.open({
                    type: 1,
                    title: title,
                    area: ['500px', '450px'],
                    content: $('#editFormTpl').html(),
                    success: function (layero, index) {
                        form.render();
                        if (data) {
                            // 修改模式：查找父节点信息
                            var parentNode = findParentNode(data.id);
                            var formData = {
                                'id': data.id,
                                'classifyName': data.classifyName,
                                'orderById': data.orderById,
                                'materialName': data.materialName,
                                'isEnabled': data.isEnabled.toString()
                            };
                            
                            // 如果找到父节点，设置父节点信息
                            if (parentNode) {
                                formData.parentId = parentNode.id;
                                formData.parentName = parentNode.classifyName;
                            } else {
                                // 如果没有父节点，说明是根节点
                                formData.parentName = '根目录';
                            }
                            
                            form.val('editForm', formData);
                        } else if (parentData) {
                            // 新增子分类模式
                            form.val('editForm', {
                                'parentId': parentData.id,
                                'parentName': parentData.classifyName,
                                'materialName': parentData.materialName,
                                'isEnabled': 'true'
                            });
                        } else {
                            // 新增根分类模式
                            form.val('editForm', {
                                'parentName': '根目录',
                                'isEnabled': 'true'
                            });
                        }
                    }
                });
            }

            // 表单提交
            form.on('submit(editFormSubmit)', function (data) {
                var loadIndex = layer.load();
                var field = data.field;
                
                var submitData = {
                    classifyName: field.classifyName,
                    orderById: parseInt(field.orderById) || 1,
                    materialName: field.materialName,
                    isEnabled: field.isEnabled === 'true',
                    parentId: field.parentId ? parseInt(field.parentId) : null
                };

                if (field.id) {
                    submitData.id = parseInt(field.id);
                }

                var url = submitData.id ? '/Material/UpdateMaterialClass' : '/Material/CreateMaterialClass';

                $.ajax({
                    url: url,
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(submitData),
                    success: function (res) {
                        layer.close(loadIndex);
                        if (res.success) {
                            layer.closeAll('page');
                            layer.msg('保存成功');
                            loadData();
                        } else {
                            layer.msg(res.message || '保存失败');
                        }
                    },
                    error: function () {
                        layer.close(loadIndex);
                        layer.msg('保存失败');
                    }
                });
                return false;
            });

            // 搜索
            form.on('submit(search)', function (data) {
                console.log('搜索参数:', data.field);
                
                // 获取搜索条件
                var searchParams = data.field;
                var className = searchParams.className || '';
                var isEnabled = searchParams.isEnabled;
                
                // 过滤数据
                var filteredData = allData;
                
                if (className || isEnabled !== '') {
                    filteredData = filterTreeData(allData, className, isEnabled);
                }
                
                // 重新渲染表格
                renderFilteredTable(filteredData);
                
                return false;
            });

            // 监听表单重置
            $('.search-area form').on('reset', function() {
                setTimeout(function() {
                    console.log('重置搜索条件');
                    // 重新渲染原始数据
                    renderTable();
                    form.render(); // 重新渲染表单
                    layer.msg('已重置搜索条件');
                }, 100);
            });

            // 过滤树形数据
            function filterTreeData(treeData, className, isEnabled) {
                var result = [];
                
                function filterNode(nodes) {
                    var filteredNodes = [];
                    
                    nodes.forEach(function(node) {
                        var matchesName = !className || node.classifyName.indexOf(className) !== -1;
                        var matchesEnabled = isEnabled === '' || 
                            (isEnabled === '1' && node.isEnabled) || 
                            (isEnabled === '0' && !node.isEnabled);
                        
                        var nodeMatches = matchesName && matchesEnabled;
                        var filteredChildren = [];
                        
                        // 递归过滤子节点
                        if (node.children && node.children.length > 0) {
                            filteredChildren = filterNode(node.children);
                        }
                        
                        // 如果节点匹配或有匹配的子节点，则包含此节点
                        if (nodeMatches || filteredChildren.length > 0) {
                            var filteredNode = Object.assign({}, node);
                            filteredNode.children = filteredChildren;
                            filteredNodes.push(filteredNode);
                        }
                    });
                    
                    return filteredNodes;
                }
                
                return filterNode(treeData);
            }

            // 渲染过滤后的表格
            function renderFilteredTable(filteredData) {
                // 重置展开状态
                expandedRows.clear();
                allExpanded = false;
                currentExpandLevel = 0;
                isExpandingMode = true;
                
                // 更新最大层级
                maxLevel = calculateMaxLevel(filteredData);
                
                // 渲染表格
                var tableData = flattenData(filteredData);
                
                table.render({
                    elem: '#materialClassTable',
                    data: tableData,
                    toolbar: '#toolbarDemo',
                    defaultToolbar: [
                        {title: '刷新', layEvent: 'refresh', icon: 'layui-icon-refresh'},
                        'exports',
                        {title: '显示/隐藏搜索', layEvent: 'toggleSearch', icon: 'layui-icon-search'}
                    ],
                    cols: [[
                        { type: 'numbers', width: 60 },
                        { 
                            field: 'classifyName', 
                            title: '分类名称', 
                            minWidth: 200, 
                            templet: function(d) {
                                var indent = '';
                                for (var i = 0; i < d._level; i++) {
                                    indent += '<span class="tree-indent"></span>';
                                }
                                
                                var hasChildren = d.children && d.children.length > 0;
                                var iconClass = hasChildren ? 
                                    (allExpanded || expandedRows.has(d.id) ? 'layui-icon-down' : 'layui-icon-right') : 
                                    'no-children';
                                var icon = '<i class="layui-icon ' + iconClass + ' tree-icon" data-id="' + d.id + '"></i>';
                                
                                return '<div class="tree-table-cell">' + indent + icon + d.classifyName + '</div>';
                            }
                        },
                        { field: 'orderById', title: '排序', width: 100 },
                        { field: 'materialName', title: '物料/产品', width: 120 },
                        {
                            field: 'isEnabled', 
                            title: '是否启用', 
                            width: 100, 
                            templet: function (d) {
                                return d.isEnabled ? 
                                    '<span class="layui-badge layui-bg-blue">是</span>' : 
                                    '<span class="layui-badge layui-bg-gray">否</span>';
                            }
                        },
                        { 
                            field: 'createTime', 
                            title: '创建时间', 
                            width: 180,
                            templet: function(d) {
                                if (!d.createTime) return '';
                                var date = new Date(d.createTime);
                                return date.toLocaleString('zh-CN');
                            }
                        },
                        { title: '操作', toolbar: '#operationBar', width: 200, fixed: 'right' }
                    ]],
                    done: function () {
                        // 绑定展开/折叠事件
                        $('.layui-table-body').off('click', '.tree-icon').on('click', '.tree-icon:not(.no-children)', function(e) {
                            e.stopPropagation();
                            var id = parseInt($(this).data('id'));
                            if (expandedRows.has(id)) {
                                expandedRows.delete(id);
                            } else {
                                expandedRows.add(id);
                            }
                            renderFilteredTable(filteredData);
                        });
                        
                        // 更新展开/折叠按钮状态
                        updateToggleButton();
                    }
                });
            }

            // 初始化
            loadData();
        });
    </script>
</body>
</html>
